<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use lib\WxpayTmd;
class Order extends Base{
    private $appid='wx897a77a94be25594';
    private $mch_id='1533591401';
    private $apikey='4hnz2zwkapo2vgdlvt1gtq2mgivhgvvi';
	// 下单
	public function orderIn()
	{
		if(!empty(input("param.openid"))){
            $data['openid']=input("param.openid");
        }else{
            return json(['code' => 501, 'msg' => '未授权']);
        }
		if(!empty(input("param.payfee"))){
			$data['payfee']=input("param.payfee");
		}else{
			return json(['code' => 502, 'msg' => '支付金额？']);
		}
		if(input("param.remark")){
			$data['remark']=input("param.remark");
		}
		$data['orderno']=date('YmdHis',time()).mt_rand(1111,9999);
		$data['state']=1;
		$data['time']=time();
		$data['uptime']=time();
		$data['paytime']=time();

		Db::startTrans();
        try {
			$orderId=Db::name('orders')->insertGetId($data);
			// 提交事务
            Db::commit();
            if($orderId){

	        $weixinpay = new WxpayTmd($this->appid,$data['openid'],$this->mch_id,$this->apikey,$data['orderno'],'当面付款',floatval($data['payfee'] * 100),$this->request->domain());
			$return=$weixinpay->pay();
                return json(['code' => 200, 'msg' => '成功！','data'=>$return]);
            }else{
                return json(['code' => 500, 'msg' => '提交事物失败！']);
            }
		} catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500, 'msg' => '事物回滚失败！']);
        }
	}
    public function notify()
    {
    	$input = file_get_contents('php://input');
        $pay_result = simplexml_load_string($input, 'SimpleXMLElement',LIBXML_NOCDATA);
        if($pay_result->result_code=='SUCCESS'&&$pay_result->return_code=='SUCCESS'){
            $paystate=Db::name('orders')->where('orderno',$pay_result->out_trade_no)->find();
            if($paystate['state']==1){
                Db::name('orders')->where('orderno',$pay_result->out_trade_no)->update(['state'=>2,'uptime'=>time(),'paytime'=>time()]);
            }
        }
    }
  	
}